
<!--
 * @Author: wang_sheshe
 * @Date: 2021-05-17 15:04:17
 * @LastEditTime: 2021-07-30 14:06:20
 * @Description: 巡视开始信息确认页
-->
<template>
	<article class="bg_4dbfae tourTaskPage">
		<!-- 头组件 -->
        <van-nav-bar title="开始信息确认" left-text="" left-arrow @click-left="back" fixed>
			<!-- <template slot="right">
				<div class="parent-circle">
					<div class="child-circle"></div>
				</div>
            </template> -->
        </van-nav-bar>
        <!-- content -->
		<van-row style="flex: 1; overflow: auto; margin-top:45px;">
			<van-field 
				label="天气"  
				placeholder="请选择" 
				readonly 
				required 
				@click="showWeather=true" 
				right-icon="arrow" 
				input-align="right"
				v-model="taskData.weather"
				@click-right-icon="showWeather=true"/>
		
			<van-field 
				label="气温(℃)" 
				required 
				:formatter="formatterAir"
				placeholder="请输入气温(℃)"
				input-align="right"
				v-model.trim="taskData.airTemperature" 
			>
			</van-field>
			<van-field 
				label="温湿度(%)" 
				required 
				placeholder="请输入温湿度(%)"
				:formatter="formatterHum"
				input-align="right" 
				v-model.trim="taskData.humiture" 
			/>
            <van-field 
				label="风速" 
				placeholder="请选择" 
				required 
				readonly
				@click="showWindspeed=true" 
				v-model="taskData.windSpeed" 
				input-align="right"
				right-icon="arrow"
				@click-right-icon="showWindspeed=true"/>
			
			<van-field 
				label="开始时间" 
				placeholder="请选择" 
				required 
				readonly
				input-align="right" 
				maxlength="25" 
				@click="showPicker=true"
				right-icon="arrow" 
				v-model="taskData.actualStartTime">
				<template slot="right-icon">
					<img :src="icon.time" @click="showPicker=true" style="width: 21px;"/>
				</template>
			</van-field>
			<div class="lineGray"></div>
			<van-field 
				label="巡视人员" 
				placeholder="请选择" 
				required 
				readonly
				input-align="right" 
                right-icon="arrow" 
				@click="showPerson=true" 
				v-model.trim="tourPersonName"
				@click-right-icon="showPerson=true"/>

			<van-row style="padding: 0 15px;color:#666;margin-top: 15px;" class="font14">备注:</van-row>
			<div style="margin: 15px;border-radius: 5px;">
				<van-field class="textarea-content" v-model.trim="taskData.remark" rows="2" autosize type="textarea" maxlength="256"
                    placeholder="请输入备注" show-word-limit />
			</div>

			<div class="doc-wrapper" v-if="taskData.patrolTypeName == '特殊巡视'">
				<van-row style="padding: 15px;color: #333;">
					<div style="width: 50%;"><span class="line_green"></span> 巡视设备列表</div>
				</van-row>
				<van-collapse v-model="activeNames" style="height: 500px;">
					<van-collapse-item v-for="(deviList,index) in showDeviceList" :key="index" :title="deviList.bayName" :name="deviList.bayId" value-class="red">
						<van-cell v-for="(device,i) in deviList.deviceList" :key="i" :title="device.deviceName"></van-cell>
					</van-collapse-item>
				</van-collapse>
			</div>
			
			<van-row class="btn-wrapper" style="text-align: center;">
				<van-button style="margin-top: 15px;" type="primary" size="small" class="c" @click="confirm">开始执行</van-button>
			</van-row>
		<!-- pop start-->
		<van-popup round v-model="showPicker" position="bottom" @close="showPicker=false">
			<!-- 时间类型选择器 -->
			<van-datetime-picker v-model="currentDate" title="选择时间" @confirm="onConfirm" @cancel="showPicker=false" 
			:min-date="minDate"
			:formatter="formatter"
  			:max-date="maxDate"
			type="datetime">
			</van-datetime-picker>
		</van-popup>
		<!-- pop end -->
		<!-- 反馈组件 天气类型-->
		<van-action-sheet title="选择天气"
			cancel-text="取消"
			@cancel="showWeather=false"
            v-model="showWeather"
            :actions="weatherList"
            @select="weatherBtn"
		/>
		
		<!-- 反馈组件 风速-->
		<van-action-sheet title="选择风速（米/秒）"
			cancel-text="取消"
			@cancel="showWindspeed=false"
            v-model="showWindspeed"
            :actions="windspeedList"
            @select="windspeedBtn"
		/>
		
		<!-- 反馈组件 巡视人员-->
		<van-popup class="selPerson" round v-model="showPerson" position="bottom" @close="showPerson=false">
			<selPople
				:userList="userList"
				@comfirmPerson="comfirmPerson" @closePersonPage="closePersonPage"
			></selPople>
		</van-popup>	
    </van-row>
	</article>
</template>

<script type="text/javascript">
	import { Tabbar, TabbarItem ,Tag } from 'vant';
	import {confirmStartInfo} from '../../api/tourTask';
	import selPople  from "@/components/SelPeople"
	import Util from "@/utils/util"
	export default {
		name: 'DefectManage',
		data() {
			return {
				showWeather: false,//天气选择开关
				showWindspeed: false,//风速选择开关
				showPerson: false,//巡视人员开关
				taskInfo: {},
				//上送数据
                taskData:{
					// patrolType: "",//巡视类型id
					// patrolTypeName: "",//巡视类型名称
					// taskId:"",//任务id
					// roleCode: "",
					// weather: "",//天气
					// airTemperature:"",//气温
					// humiture: "",//温湿度
					// windSpeed: "",//风速
					// actualStartTime: "",//开始时间
					// remark: "",//备注
				},
                showPicker:false,
                currentDate: new Date(),//选择时间 
				weatherList: [
				],
				windspeedList:[
				],
				userList: [],//巡视人员列表
				tourPersonName: "",//巡视人员 供页面显示
				icon: {
					"time": require("@assets/img/mainIndex/time.png"),
				},
				showDeviceList: [],//展示设备数据
				seldeviceList: [],//源设备数据
				activeNames:[],
				userInfo:{},
				minDate: new Date(new Date().getFullYear()-2,new Date().getMonth()+1,new Date().getDay()),
				maxDate: new Date(new Date().getFullYear()+2,new Date().getMonth()+1,new Date().getDay()),
			}
		},
		
		components: {
			selPople
		},
		
		methods: {
			//日期格式
			formatter(type, val) {
				if (type === 'year') {
					return val + '年';
				}
				if (type === 'month') {
					return val + '月';
				}
				if (type === 'day') {
					return val + '日';
				}
				if (type === 'hour') {
					return val + '时';
				}
				if (type === 'minute') {
					return val + '分';
				}
				return val;
			},
			//湿度
			formatterHum(value) {
				if( 0 < value && value < 100){
					return value;
				}else{
					return "";
				}
			},
			//气温格式
			formatterAir(value) {
				var t = value.charAt(0);
				//过滤非数字，除了数字和1.
				var code = value.replace(/[^\d.]/g,"");
				//保证第一个为数字而不是.
				code = code.replace(/^\./g,"");
				//保证只出现一个点
				code = code.replace(/\.{2,}/g,".");
				code = code.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
				code = code.replace(/^(\-)*(\d+)\.(\d).*/,"$1$2.$3")
				if(code.indexOf(".") < 0) {
					if(code.substr(0,1)=='0') {
						code = code.substr(1,3)
					}else{
						code = code.substr(0,2)
					}
				}
				if(t == "-") {
					code = "-"+code;
				}
				return code;
			},
            /**
            * @description: 开始执行
            * @param {*}
            * @return {*}
            */         
			confirm(){
				this.isCheckedParam();
			},
			//时间选择
            onConfirm(val){
				this.showPicker = false;
            	this.taskData.actualStartTime = Util.DateUtil.getFormatDateByLong(val,'yyyy-MM-dd hh:mm')
            },
            onCancel(){

            },
			/**
			 * 返回
			 */
			back(){
				history.go(-1)
			},
			loginOutbtn(){
				
			},
			//天气
			weatherBtn(val) {
				this.showWeather = false;
				this.taskData.weather = val.name;
			},
			//风速
			windspeedBtn(val) {
				this.showWindspeed = false;
				this.taskData.windSpeed = val.name;
			},
			/**
			* @description: 参数校验
			* @param {*}
			* @return {*}
			*/
			isCheckedParam() {
				if(Util.baseUtil.isEmptyString(this.taskData.weather)) {
					this.$Toast.fail("请选择天气!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.taskData.airTemperature)) {
					this.$Toast.fail("请填写气温!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.taskData.humiture)) {
					this.$Toast.fail("请填写温湿度!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.taskData.windSpeed)) {
					this.$Toast.fail("请选择风速!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.taskData.actualStartTime)) {
					this.$Toast.fail("请选择开始时间!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.tourPersonName)) {
					this.$Toast.fail("请选择巡视人员!")
					return;
				}
				// if(Util.baseUtil.isEmptyString(this.taskData.remark)) {
				// 	this.$Toast.fail("请选择任务备注!")
				// 	return;
				// }
				this.beginTourTask();
			},
			/**
			* @description: 开始巡视任务
			* @param {*}
			* @return {*}
			*/
			beginTourTask() {
				var self = this,list=[];
				var time = new Date(this.taskData.actualStartTime).getTime();
				this.userList.forEach(item => {
					list.push({
						patrolStaffId: item.userId,
						patrolStaffName:item.userName 
					})
				})
				var params = {
					taskId: this.taskData.id,//任务id
					airTemperature: this.taskData.airTemperature,////气温
					humiture: this.taskData.humiture,//温湿度
					userList: list,
					windSpeed: this.taskData.windSpeed,//风速
					weather: this.taskData.weather,//天气
					patrolStartTime: time,//开始时间
					remark: this.taskData.remark,//备注
					userId: this.userInfo.userId,
					roleCode: this.taskData.roleCode,	
				};
				this.$Toast.loading({
						duration: 0,//展示时长 0不会消失
						message: "巡视任务创建中...",
						forbidClick: true,//是否禁止背景点击
						overlay: true//是否显示背景遮罩层
					})
				confirmStartInfo(params).then(data => {
					self.$Toast.clear();
					if(data.success) {
						self.$Toast.success(data.msg)
						self.goDetailPath();
						//self.$router.push({name:"tourTaskIndex",params:{}})
					}else{
						self.$Toast.fail(data.msg)
					}
				}).catch(err => {
					self.$Toast.fail(err)
				})
			},
			/**
			* @description: 巡视类型不同跳转页面路径不同
			* @param {*}
			* @return {*}
			*/
			goDetailPath(){
				if(this.taskData.patrolTypeName == "全面巡视") {
					this.$router.push({//执行页面
						name:"executeIndex",
						params:
							{
								deviceList: this.seldeviceList,
								taskInfo: this.taskData
							}
					})
				}else{
					this.$router.push({
						name:"finish",
						params:
							{
								deviceList: this.seldeviceList,
								taskInfo: this.taskData
							}
					})	
				}
			},
			/**
			* @description: 人员选择回调
			* @param {*}
			* @return {*}
			*/
			comfirmPerson(personList) {
				this.showPerson = false;
				this.userList = personList;
				this.tourPersonName = personList.map(item => item.userName).join(",");
			},
			/**
			* @description: 关闭人员组件
			* @param {*}
			* @return {*}
			*/
			closePersonPage() {
				this.showPerson = false;
			},
			//渲染数据
			renderData() {
				this.taskData.userList.forEach(item => {
					this.userList.push({
						userId: item.patrolStaffId,
						userName:item.patrolStaffName 
					})
				})
				this.tourPersonName = this.userList.map(item => item.userName).join(",");
			},
			/**
			* @description: 处理设备格式(将相同的间隔设备归纳一起) 间隔-设备
			* @param {*}
			* @return {*}
			*/
			dealDevice(taskInfo) {
				this.seldeviceList = [];
				if(taskInfo.deviceList && taskInfo.deviceList.length > 0) {
					var obj = [];
					for(var i in taskInfo.deviceList) {
						if(obj.indexOf(taskInfo.deviceList[i].bayId) === -1) {
							this.seldeviceList.push({
								bayName: taskInfo.deviceList[i].bayName,
								bayId: taskInfo.deviceList[i].bayId,
								deviceList:[taskInfo.deviceList[i]]
							})
							obj.push(taskInfo.deviceList[i].bayId);
						}else{
							for(var j in this.seldeviceList) {
								if(this.seldeviceList[j].bayId == taskInfo.deviceList[i].bayId) {
									this.seldeviceList[j].deviceList.push(taskInfo.deviceList[i]);
									break;
								}
							}
						}
					}
				}
				console.log("this.seldeviceList",this.seldeviceList)
				this.showDeviceList = JSON.parse(JSON.stringify(this.seldeviceList))
			}
		},
		mounted() {
			var userInfo = localStorage.getItem("userInfo");
			this.userInfo = JSON.parse(userInfo);
			this.weatherList = Util.baseUtil.getSpecialCode("WEATHER");
			this.windspeedList = Util.baseUtil.getSpecialCode("WIND_SPEED");
			//任务详情
			var taskInfo = this.$route.params.taskInfo;
			if(taskInfo && taskInfo.deviceList) {
				this.taskData = taskInfo;
				this.renderData();
				this.dealDevice(taskInfo);
			}else{
				this.$Toast.fail("未获取任务详情数据或设备收据！")
				return;
			}
		},
		
	}
</script>

<style scoped>
	article {
		display: flex;
		flex-direction: column;
		height: 100vh;
        font-family: 微软雅黑;
        background: #ffffff;
	}
	.active{
		color: #36BDA6 !important;
		background: #ECF6F4 !important;
	}
	.van-nav-bar__text,.van-nav-bar .van-icon{
		color: #333333;
    }
    .van-button--default {
        margin-right: 20px !important;
        width: 80px;
    }
    .van-button--primary {
		background-color: #17B49B;
        border: 0.02667rem solid #17B49B;
        color: white;
		width: 138px;
        margin: 0 auto;
    }
	.templateDiv{
		display: flex;
		justify-content: space-between;
		padding: 10px 15px;
	}
	.van-checkbox-part{
		display: inline;margin-right: 15px;
	}
	input{
        width: calc(100% - 20px);
        margin: 0px 10px;
        box-sizing: border-box;
		height: 60px;
		border: 1px solid #E2E2E2;
		border-radius: 3px;
    }
	.personClass /deep/ .van-nav-bar__text{
		font-size: 14px !important;
	}
	.personClass /deep/ .van-nav-bar__title{
		font-size: 16px !important;
	}
	.selPerson{
		height:100%;width:100%;
	}  
	.doc-wrapper{
		margin: 0.2rem 0.26667rem 0 0.4rem;
		background: white;
		border-radius: 10px;
	}
	.line_green{
		display: inline-block;
		height: 16px;
		width: 3px;
		background: #17B49B;
		border-radius: 3px;
		position: relative;
		top: 3px;
	}
	.textarea-content{
		border: 1px solid #E2E2E2;color:#999;
	}
	.btn-wrapper{
		position: fixed;
		width: 100%;
		text-align: center;
		bottom: 10px;
	}
</style>
